import { Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository, Not, IsNull } from 'typeorm'
import { CreateLogDto } from './dto/create-log.dto'
import { UpdateLogDto } from './dto/update-log.dto'
import { Log } from './entities/log.entity'
const moment = require('moment')
@Injectable()
export class LogService {
  constructor(@InjectRepository(Log) private readonly log: Repository<Log>) {}
  create(createLogDto: CreateLogDto) {
    return 'This action adds a new log'
  }

  async findAll(params: {
    page: number
    pageSize: number
    isDelete?: boolean
  }) {
    const where = {}
    params.isDelete && (where['deleteDate'] = Not(IsNull()))
    const data = await this.log.find({
      where: { ...where },
      withDeleted: params.isDelete,
      skip: (params.page - 1) * params.pageSize,
      take: params.pageSize,
      order: { id: 'DESC' }
    })
    const total = await this.log.count({
      where: { ...where },
      withDeleted: params.isDelete
    })
    return { data, total }
  }

  async findOne(id: number) {
    return await this.log.findOne({ where: { id } })
  }
  // 根据模块分组返回操作数据
  async getModule() {
    const data = await this.log.query(`
    SELECT
      url,
      COUNT(*) AS count
    FROM
      log
    GROUP BY
      url`)
    const newDate = [
      { module: '其他', count: 0 },
      { module: '登录模块', count: 0 }
    ]
    const urlList = [
      'staff',
      'admin',
      'auth',
      'img',
      'department',
      'work-state',
      'role',
      'log',
      'notice',
      'award-rule',
      'job',
      'account',
      'upload',
      'apply',
      'award',
      'changeSalary',
      'transfer',
      'salary',
      'login',
      'logout'
    ]
    const moduleList = [
      '员工模块',
      '管理员模块',
      '权限模块',
      '图片模块',
      '部门模块',
      '工作状态模块',
      '角色模块',
      '日志模块',
      '公告模块',
      '奖惩规则模块',
      '工资模块',
      '账套模块',
      '上传模块',
      '申请模块',
      '奖惩模块',
      '调薪模块',
      '调动模块',
      '工资模块',
      '登录模块'
    ]
    data.map(item => {
      const url = item.url.split('/')[1]
      if (url === 'login' || url === 'logout') {
        newDate[1].count += +item.count
        return
      } else if (!urlList.includes(url)) {
        newDate[0].count += +item.count
        return
      }
      const x = {
        module: moduleList[urlList.indexOf(url)],
        count: +item.count
      }
      const index = newDate.findIndex(item => item.module === x.module)
      index === -1 ? newDate.push(x) : (newDate[index].count += x.count)
    })
    return newDate
  }
  // 获取操作信息按时间分组 0-6 6-12 12-18 18-24
  async getTime() {
    const data = await this.log.query(`
    SELECT
      COUNT(*) AS count,
      DATE_FORMAT(
        create_date,
        '%H'
      ) AS time
    FROM
      log
    GROUP BY
      time`)
    const newDate = [
      { time: '0-6', count: 0 },
      { time: '6-12', count: 0 },
      { time: '12-18', count: 0 },
      { time: '18-24', count: 0 }
    ]
    data.map(item => {
      const time = +item.time
      if (time >= 0 && time < 6) {
        newDate[0].count += +item.count
      } else if (time >= 6 && time < 12) {
        newDate[1].count += +item.count
      } else if (time >= 12 && time < 18) {
        newDate[2].count += +item.count
      } else if (time >= 18 && time < 24) {
        newDate[3].count += +item.count
      }
    })
    return newDate
  }
  // 获取操作信息按天分组近七天
  async getDay() {
    const data = await this.log.query(`
    SELECT
      COUNT(*) AS count,
      DATE_FORMAT(
        create_date,
        '%m-%d'
      ) AS time
    FROM
      log
    Where
      create_date >= CURDATE() - INTERVAL 7 DAY
    GROUP BY
      time`)
    // 7天内没有操作的日期补0
    const date = []
    for (let i = 6; i >= 0; i--) {
      const time = moment().subtract(i, 'days').format('MM-DD')
      date.push(time)
    }
    const newData = []
    date.map(item => {
      const index = data.findIndex(i => i.time === item)
      if (index === -1) {
        newData.push({ time: item, count: 0 })
      } else {
        newData.push(data[index])
      }
    })
    return newData
  }

  // 按操作类型 统计用户的操作行为 增删改查
  async getMethod() {
    const data = await this.log.query(`
    SELECT
      method,
      COUNT(*) AS count
    FROM
      log
    GROUP BY
      method`)
    return data
  }
  // 按操作结果 统计用户的操作行为
  async getCode() {
    const data = await this.log.query(`
    SELECT
      code,
      COUNT(*) AS count
    FROM
      log
    GROUP BY
      code`)
    return data.map(item => ({
      code: '' + item.code,
      count: +item.count
    }))
  }

  // 按用户 统计用户的操作行为 用户名 用户角色 用户部门 用户职位
  async getUser(
    staffId?: number,
    roleId?: number,
    departmentId?: number,
    jobId?: number
  ) {
    const where = {}
    staffId && (where['staff.id'] = staffId)
    roleId && (where['role.id'] = roleId)
    departmentId && (where['department.id'] = departmentId)
    jobId && (where['job.id'] = jobId)
    const data = await this.log.query(`
    SELECT
      DATE_FORMAT(log.create_date, '%Y-%m-%d') AS time,
      COUNT(*) AS count
    FROM
      log
    LEFT JOIN staff ON staff.id = log.staff_id
    LEFT JOIN admin ON admin.staff_id = staff.id
    LEFT JOIN role ON role.id = admin.role_id
    LEFT JOIN department ON department.id = staff.department_id
    LEFT JOIN job ON job.id = staff.job_id
    WHERE
      ${Object.keys(where)
        .map(item => `${item} = ${where[item]}`)
        .join(' AND ')}
    AND
      log.create_date >= CURDATE() - INTERVAL 7 DAY
    GROUP BY
      time`)
    // 7天内没有操作的日期补0
    const date = []
    for (let i = 6; i >= 0; i--) {
      const time = moment().subtract(i, 'days').format('YYYY-MM-DD')
      date.push(time)
    }
    const newData = []
    date.map(item => {
      const index = data.findIndex(i => i.time === item)
      if (index === -1) {
        newData.push({ time: item, count: 0 })
      } else {
        newData.push(data[index])
      }
    })
    return newData
  }

  update(id: number, updateLogDto: UpdateLogDto) {
    return this.log.update(id, updateLogDto)
  }

  remove(ids: number[]) {
    return this.log.softDelete(ids)
  }

  thoroughRemove(ids: number[]) {
    return this.log.delete(ids)
  }

  restore(ids: number[]) {
    return this.log.restore(ids)
  }
}
